package cz.acies.data.dao;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;

import cz.acies.data.DBConnector;
import cz.acies.uniql.metadata.DBMetaData;
import cz.acies.uniql.sql.SelectQuery;
import cz.acies.uniql.sql.element.UniQLCondition;
import cz.acies.uniql.sql.element.UniQLWhere;

public abstract class AbstractDAO
{
	protected String tableName = "";
	
	public boolean existsRecord(String id) throws Exception {
		try {
			SelectQuery sql = new SelectQuery(dbmd()).addFrom(tableName).add(new UniQLCondition(tableName+".id", "=", "'"+id+"'"));
			QueryRunner qr = new QueryRunner(DBConnector.instance().getDataSource());
			List<Map<String, Object>> list = qr.query(sql.toSQLString(), new DefaultMapListHandler(new DefaultRowProcessor()));
			return !list.isEmpty();  
		} catch (Exception exc) {
			throw exc; //exc.printStackTrace();
		}
		//return false;
	}

	public boolean existsRecord(UniQLWhere where) throws Exception {
		try {
			SelectQuery sql = new SelectQuery(dbmd()).addFrom(tableName).addWhere(where);
			QueryRunner qr = new QueryRunner(DBConnector.instance().getDataSource());
			List<Map<String, Object>> list = qr.query(sql.toSQLString(), new DefaultMapListHandler(new DefaultRowProcessor()));
			return !list.isEmpty();  
		} catch (Exception exc) {
			throw exc; //exc.printStackTrace();
		}
		//return false;
	}

	// -----  -----------------------------------------------------------------
	
	public DBMetaData dbmd() {
		return DBConnector.instance().dbmd();
	}
	
	public DataSource ds() {
		return DBConnector.instance().getDataSource();
	}

}
